package com.rightsidetech.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.PageRequest;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.exception.BizException;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.RuleCommoditySaveReq;
import com.rightsidetech.system.dtos.request.RuleCommoditySpecsSaveReq;
import com.rightsidetech.system.dtos.request.RuleCommodityUpReq;
import com.rightsidetech.system.dtos.request.SysRuleStatusReq;
import com.rightsidetech.system.dtos.response.SysRuleCommodityDetailResp;
import com.rightsidetech.system.dtos.response.SysRuleCommodityPageResp;
import com.rightsidetech.system.dtos.response.SysRuleSpecsDetailResp;
import com.rightsidetech.system.entity.SysRuleCommodityIntegral;
import com.rightsidetech.system.mapper.SysRuleCommodityIntegralMapper;
import com.rightsidetech.system.service.SysRuleCommodityIntegralService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.math.BigDecimal;
import java.util.*;

@Service("sysRuleCommodityIntegralService")
public class SysRuleCommodityIntegralServiceImpl implements SysRuleCommodityIntegralService {

    @Resource
    private SysRuleCommodityIntegralMapper sysRuleCommodityIntegralMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData save(RuleCommoditySaveReq req) throws Exception {
        if (sysRuleCommodityIntegralMapper.selectCountByCommodityId(req.getCommodityId()) > 0) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此商品已经创建过积分规则");
        }
        SysRuleCommodityIntegral record = new SysRuleCommodityIntegral();
        record.setCommodityName(req.getCommodityName());
        record.setParentId(0L);
        record.setCommodityId(req.getCommodityId());
        record.setRuleValue(req.getRuleValue());
        record.setRuleStatus((byte) 0);
        record.setCreatedAt(new Date());
        if (sysRuleCommodityIntegralMapper.insertSelective(record) <= 0) {
            throw new BizException(CodeIdEnum.FAILED);
        }
        saveChild(req, record.getId());
        return ResponseData.success(CodeIdEnum.Success);
    }

    private void saveChild(RuleCommoditySaveReq req, Long parentId) throws BizException {
        List<RuleCommoditySpecsSaveReq> list = req.getList();
        if (CollUtil.isNotEmpty(list)) {
            Map<String, Object> map = new HashMap<>();
            map.put("commodityId", req.getCommodityId());
            map.put("commodityName", req.getCommodityName());
            map.put("parentId", parentId);
            map.put("list", list);
            if (sysRuleCommodityIntegralMapper.insertList(map) <= 0) {
                throw new BizException(CodeIdEnum.FAILED);
            }
        }
    }

    @Override
    public ResponseData<PageInfo<SysRuleCommodityPageResp>> page(PageRequest req) {
        PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<SysRuleCommodityPageResp> result = sysRuleCommodityIntegralMapper.selectPageList();
        if (CollUtil.isNotEmpty(result)) {
            for (SysRuleCommodityPageResp resp : result) {
                if (resp.getCount() <= 0) {
                    resp.setChildren(null);
                    resp.set_loading(null);
                }else {
                    resp.setRuleValue(null);
                }
            }
        }
        return ResponseData.success(new PageInfo<>(result));
    }

    @Override
    public ResponseData<List<SysRuleCommodityPageResp>> getChild(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<SysRuleCommodityPageResp> result = sysRuleCommodityIntegralMapper.selectListByParentId(req.getId());
        if (CollUtil.isNotEmpty(result)) {
            for (SysRuleCommodityPageResp pageResp : result) {
                pageResp.setChildren(null);
                pageResp.set_loading(null);
                pageResp.setCommodityName(null);
            }
        }
        return ResponseData.success(result);
    }

    @Override
    public ResponseData<SysRuleCommodityDetailResp> detail(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysRuleCommodityIntegral ruleCommodityIntegral = sysRuleCommodityIntegralMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(ruleCommodityIntegral)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到此规则");
        }
        SysRuleCommodityDetailResp result = new SysRuleCommodityDetailResp();
        result.setId(ruleCommodityIntegral.getId());
        result.setCommodityName(ruleCommodityIntegral.getCommodityName());
        result.setCommodityId(ruleCommodityIntegral.getCommodityId());
        result.setRuleValue(ruleCommodityIntegral.getRuleValue());
        List<SysRuleSpecsDetailResp> list = sysRuleCommodityIntegralMapper.selectDetail(ruleCommodityIntegral.getId());
        result.setList(list);
        return ResponseData.success(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData update(RuleCommodityUpReq req) throws Exception {
        SysRuleCommodityIntegral integral = sysRuleCommodityIntegralMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(integral)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "为找到需要修改的数据");
        }
        sysRuleCommodityIntegralMapper.delByParentId(integral.getId());
        saveChild(req, integral.getId());
        integral = new SysRuleCommodityIntegral();
        integral.setId(req.getId());
        integral.setRuleValue(req.getRuleValue());
        if (sysRuleCommodityIntegralMapper.updateByPrimaryKeySelective(integral) <= 0) {
            throw new BizException(CodeIdEnum.FAILED);
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData updateStatus(SysRuleStatusReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData<>(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysRuleCommodityIntegral integral = sysRuleCommodityIntegralMapper.selectByPrimaryKey(req.getId());
        if (ObjectUtil.isEmpty(integral)) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "未找到需要操作的规则");
        }
        if (integral.getRuleStatus().equals(req.getRuleStatus())) {
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(), "此积分规则已经是开启/关闭状态，不允许重复操作");
        }
        if(integral.getParentId() == 0){
            sysRuleCommodityIntegralMapper.updateChileByParentId(integral.getId(),req.getRuleStatus());
        }else {
            if(req.getRuleStatus() == 0){
                sysRuleCommodityIntegralMapper.updateRuleStatusById(integral.getParentId(),req.getRuleStatus());
            }
        }
        integral = new SysRuleCommodityIntegral();
        integral.setId(req.getId());
        integral.setRuleStatus(req.getRuleStatus());
        if (sysRuleCommodityIntegralMapper.updateByPrimaryKeySelective(integral) <= 0) {
            return ResponseData.fail(CodeIdEnum.FAILED);
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public BigDecimal findRuleValueByIdAndBarCode(Long commodityId, String barCode) {
        SysRuleCommodityIntegral rule = sysRuleCommodityIntegralMapper.selectByCommodityIdAndBarCode(commodityId,barCode);
        if(ObjectUtil.isNotEmpty(rule)){
            return rule.getRuleValue();
        }
        return null;
    }
}
